package com.mooc.ad.service;

import com.imooc.ad.util.JsonUtil;
import com.mooc.ad.entity.Cart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * Created by lzq on 2019/3/14
 */
@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    static final String CART_KEY_PREFIX = "cart:uid:";

    /**
     * 添加购物车
     * @param cart
     */
    public void addCart(Cart cart) {

        Long userId=111L;

        //redis key
        String key=CART_KEY_PREFIX+userId;

        //绑定key 获取hash对象

        BoundHashOperations<String, Object, Object> hashOps = this.redisTemplate.boundHashOps(key);
        // 查询是否存在
        Long skuId = cart.getSkuId();
        Integer num = cart.getNum();
        Boolean added = hashOps.hasKey(skuId.toString());
        //用户之前是否添加过购物车
        if(added){
            //添加过
            String cartJson = hashOps.get(skuId.toString()).toString();
            cart = JsonUtil.parse(cartJson, Cart.class);
            // 修改购物车数量
            cart.setNum(cart.getNum() + num);
        }else {
            //未添加过此商品
            // 不存在，新增购物车数据
            cart.setUserId(userId);
            // 其它商品信息， 需要查询商品服务
            //Sku sku = this.goodsClient.querySkuById(skuId);
            cart.setImage("");
            cart.setPrice(50l);
            cart.setTitle("haha");
            cart.setOwnSpec("这是啥");
        }
        hashOps.put(skuId.toString(),JsonUtil.serialize(cart));

    }
}
